package ru.vms.healthcontrol;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import ru.vms.healthcontrol.RequestResult.ReqType;

import loc.org.json.JSONException;
import loc.org.json.JSONObject;
import loc.org.json.JSONTokener;

import android.accounts.NetworkErrorException;
import android.content.Context;

public class GatewayUtil {

	private static final int POST_TIMEOUT = 10 * 1000;
	public final static String GatewayHost = "http://atlant-inform.dyndns.org/medservice/index.php"; 
	private Context context;

	public GatewayUtil ( Context c ) {
		this.context = c;
	}
	
	public void testSimplePost () {
		
		String request = "{\"request\":\"authorize\",\"values\":{\"v_login\":\"9hushker@gmail.com\",\"v_password\":\"12345\",\"v_nmnickname\":\"nick2\"}}";
		String response = sendSimplePost(request);
		NetLog.i("resp: %s", response);
	}
	
	public RequestResult authorization ( UserData user ) throws JSONException, Exception {
		
			NotumAccountBean account = new NotumAccountBean(user);
			
			JSONObject auth_obj = new JSONObject();
			auth_obj.put("request", "authorize");
			auth_obj.put("values", new JSONObject(account));
			
			String response = sendSimplePost(auth_obj.toString());
			if ( response.length() <= 0 )
				throw new NetworkErrorException("Send POST failed");
			
			NetLog.v("%s", response );
			
			JSONTokener tokener = new JSONTokener(response);
			
			JSONObject root = (JSONObject) tokener.nextValue();
			
			return new RequestResult(root,ReqType.AUTHORIZATION);
		
	}
	
	private String sendSimplePost(String msg) {

		String lineEnd = "\r\n" ;
		String result = new String("");
	    HttpURLConnection connection = null ;
	    DataOutputStream outputStream = null ;
	     
	    
		String sURL = ( GatewayHost );

		try {
			URL url = new URL(sURL);
			connection = (HttpURLConnection) url.openConnection();
			HttpURLConnection.setFollowRedirects(false);
			connection.setConnectTimeout(POST_TIMEOUT);

			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			// Enable POST method
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");

			outputStream = new DataOutputStream(connection.getOutputStream());

			outputStream
					.writeBytes(lineEnd + lineEnd + msg + lineEnd + lineEnd);
			outputStream.flush();

			int respCode = connection.getResponseCode();
			NetLog.i("server response code: %d", respCode);


			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = null;
			StringBuilder json_response = new StringBuilder();
			while ((line = br.readLine()) != null) {
				json_response.append(line);
			}
			br.close();
			
			if ( json_response.length() > 0 )
				result = json_response.toString(); 
			else
				NetLog.e("json_response.length() <= 0");
			
			
		} catch (MalformedURLException e) {
			NetLog.e("%s",e.toString());
			e.printStackTrace();
		} catch (ProtocolException e) {
			NetLog.e("%s",e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			NetLog.e("%s",e.toString());
			e.printStackTrace();
		} catch ( Exception e ) {
			NetLog.e("%s",e.toString());
		} finally {
			if( connection != null)
				connection.disconnect();
		}

		return result;
	}
	
	
	public class NotumAccountBean {

		String v_login = null;
		String v_password = null;
		String v_nmnickname = null;
		
		public NotumAccountBean(UserData user) {
			this.v_login = user.getLogin();
			this.v_password = user.getPassword();
			this.v_nmnickname = user.getNick();
		}

		public String getV_login() {
			return v_login;
		}

		public void setV_login(String v_login) {
			this.v_login = v_login;
		}

		public String getV_password() {
			return v_password;
		}

		public void setV_password(String v_password) {
			this.v_password = v_password;
		}

		public String getV_nmnickname() {
			return v_nmnickname;
		}

		public void setV_nmnickname(String v_nmnickname) {
			this.v_nmnickname = v_nmnickname;
		}
		
		
	}
}

